package com.huawei.crm.web.controller;

import com.huawei.crm.domain.Department;
import com.huawei.crm.query.QueryObject;
import com.huawei.crm.service.IDepartmentService;
import com.huawei.crm.util.JsonResult;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private IDepartmentService service;

    @RequestMapping("/list")
    // value: 指定当前方法需要的权限
    // logical: 设置当前用户是否是必须拥有所有的权限才能访问当前的方法
    // AND: 同时拥有,默认值
    // OR: 拥有其中任何一个即可
    @RequiresPermissions(value = {"部门列表","department:list"}, logical = Logical.OR)
    public String list(Model model, QueryObject qo) {
        model.addAttribute("pageInfo", service.query(qo));
        return "department/list";
    }

    @RequestMapping("/delete")
    @RequiresPermissions(value = {"部门删除","department:delete"}, logical = Logical.OR)
    @ResponseBody
    public JsonResult delete(Long id) {
        JsonResult result = new JsonResult();
        try {
            if (id != null) {
                service.delete(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("亲,删除失败");
        }
        return result;
    }

    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"部门保存或修改","department:saveOrUpdate"}, logical = Logical.OR)
    @ResponseBody // 将返回值转换成json格式的字符串并响应给页面
    public JsonResult saveOrUpdate(Department d) {
        JsonResult result = new JsonResult();
        try {
            service.saveOrUpdate(d);
        } catch (Exception e) {
            e.printStackTrace();
            result.mark("亲,操作失败!");
        }
        return result;
    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"部门编辑","department:input"}, logical = Logical.OR)
    public String input(Model model, Long id) {
        if (id != null) {
            Department d = service.get(id);
            model.addAttribute("d", d);
        }
        return "department/input";
    }
}
